package com.metaverse.backend.utils.excel;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.lang.reflect.Method;

public class EnumConverter implements Converter {

    private Class enumClass;

    public EnumConverter(Class  clazz){
        if(!clazz.isEnum()){
            throw new IllegalArgumentException("只支持枚举类型");
        }
        this.enumClass = clazz;
    }

    @Override
    public Class supportJavaTypeKey() {
        return enumClass;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return null;
    }

    @Override
    public Object convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return null;
    }

    @Override
    public CellData convertToExcelData(Object o, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        if(o == null){
            return null;
        }

        try {
            Method mo = o.getClass().getMethod("getDescription");
            return new CellData(mo.invoke(o));
        } catch (Exception e) {
            //ignore
            return new CellData(((Enum)o).name());
        }


    }
}
